package com.fitmanagement.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.fitmanagement.entity.Users;
import com.fitmanagement.exception.ServiceException;
import com.fitmanagement.mapper.UsersMapper;
import jakarta.annotation.Resource;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private UsersMapper usersMapper;

    private static final String SECRET_KEY = "mySecretKeyForJwt";  // 从配置文件中获取

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || token.trim().isEmpty() || !token.startsWith("Bearer ")) {
            token = request.getParameter("token");
        }

        if (token == null || token.trim().isEmpty()) {
            throw new RuntimeException("无token，请重新登录");
        }

        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);  // 获取token中的userId
        } catch (JWTDecodeException j) {
            throw new ServiceException("1", "无效的token");
        }

        int userIdInt;
        try {
            userIdInt = Integer.parseInt(userId);  // 确保userId有效
        } catch (NumberFormatException e) {
            throw new ServiceException("1", "无效的token");
        }

        // 根据用户ID查询数据库
        Users user = usersMapper.selectById(userIdInt);
        if (user == null) {
            throw new RuntimeException("用户不存在，请重新登录！");
        }

        // 使用固定的密钥进行JWT验证
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
        try {
            jwtVerifier.verify(token);  // 验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException("1", "请登录");
        }

        return true;
    }
}

